import type { PluginOption } from 'vite';
var urlMoudule = require("url");
var qs = require("querystring")
const fs = require('fs')
const path = require('path')
//var gotSend = require('got') //使用import也可以 import gotSend from 'got';
import gotSend from 'got';
const superagent = require('superagent');
//https://blog.csdn.net/qq_36380426/article/details/125611378
//https://blog.csdn.net/weixin_42614080/article/details/124898388
export default function vitePluginCodegen(): PluginOption {
	return {
		// 插件名称
		name: 'vite-plugin-codegen',

		// pre 会较于 post 先执行
		enforce: 'pre', // post

		// 指明它们仅在 'build' 或 'serve' 模式时调用
		apply: 'serve', // apply 亦可以是一个函数

		config(config, { command }) {
			//console.log('这里是config钩子');
		},

		configResolved(resolvedConfig) {
			//console.log('这里是configResolved钩子');
		},
		//https://cn.vitejs.dev/guide/api-plugin.html#vite-specific-hooks
		//https://www.cnblogs.com/fly_dragon/p/9186722.html?ivk_sa=1024320u
		//https://blog.csdn.net/NI_computer/article/details/109362820
		configureServer(server) {
			//console.log('这里是configureServer钩子');
			return () => {
				server.middlewares.use((req, res, next) => {//req:http.IncomingMessag
					//console.log('这里是configResolved钩子333：' + req.url + "-")
					 // 调用res.end()方法，向服务器响应一些内容
				    res.setHeader("Content-Type", 'text/html; charset=utf-8')
					var url = req.url;
					var method = req.method;
					var urlObj = urlMoudule.parse(url);
					//let urlObj= new URL(url); 
					// console.log(urlObj, method);
					var query = urlObj.query;
					var pathname = urlObj.pathname;
					query = qs.parse(query);
					if (url === '/codegen/menusave.html') {//req.method
						var buffer = Buffer.alloc(0)
						//新建一个buffer
						req.on("data", function(data) {
							//使用监听，当获取到新数据时，将其加入到buffer中
							buffer += data;
							req.on("end", function() {
								//当不再获取新数据时，使用buffer模块中的tosrting方法将buffer转换为string类型，
								//并用querystring中的parse将查询字符串转换为对象
								//console.log(qs.parse(buffer.toString()));
								var params = JSON.parse(JSON.stringify(buffer))
								const configFile = path.resolve(__dirname, '../../router/modules/localAsyncRoutes.json')
								//fs.writeFile(configFile, params)
								fs.writeFile(configFile, params, function(err: any) {
									if (err) throw err;
									res.end(JSON.stringify({ status: true, msg: "写入成功！" }))
								});
								//console.log(JSON.parse(JSON.stringify(buffer)));
								//[Object: null prototype] { name: '23', age: '123' }
							})
						})
						//res.end('Hello vite pluginww' + req)
					} else if (url === '/codegen/menulist.html') {
						const configFile = path.resolve(__dirname, '../../router/modules/localAsyncRoutes.json')
						const data = fs.readFileSync(configFile, 'UTF-8').toString()
						let dataobj = JSON.parse(data)
						res.end(JSON.stringify({ status: true, msg: "读取成功！", data: dataobj }))
					} else if (url === '/codegen/ajax_request.html') {
						var buffer = Buffer.alloc(0)
						//新建一个buffer
						req.on("data", function(data) {
							//使用监听，当获取到新数据时，将其加入到buffer中
							buffer += data;
							req.on("end", function() {
								var params = JSON.parse(buffer.toString())
								//console.log(params)
								superagent.get(params.url).then(res2 => {
									res.end(JSON.stringify({ status: true, msg: "读取成功！", data:JSON.parse( res2.text )}))
								}).catch(err2 => {
									console.error(err2)
								});
							})
						})
					} else {
						next()
					}
					/*
					res.writeHead(200, "ok", {
						"content-type": 'text/plain;charset=utf-8'
					});
					console.log(query, pathname);
				    
					if (method == 'GET') {
						console.log(query);
					} else {
						var buffer = Buffer.alloc(0)
						//新建一个buffer
						req.on("data", function(data) {
							//使用监听，当获取到新数据时，将其加入到buffer中
							buffer += data;
							req.on("end", function() {
								//当不再获取新数据时，使用buffer模块中的tosrting方法将buffer转换为string类型，
								//并用querystring中的parse将查询字符串转换为对象
								console.log(qs.parse(buffer.toString()));
								//[Object: null prototype] { name: '23', age: '123' }
							})
						})

					}
 */
				})
			}
		},

		transformIndexHtml(html) {
			//console.log('这里是transformIndexHtml钩子');
		},
	}
}